/**
 *     Copyright (C) 2009 Anders Aagaard <aagaande@gmail.com>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.neuron.trafikanten.views.route;

import java.util.ArrayList;

import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

import com.neuron.trafikanten.R;
import com.neuron.trafikanten.dataSets.StationData;
import com.neuron.trafikanten.search.StationSearchProvider;
import com.neuron.trafikanten.tasks.ShowTipsTask;
import com.neuron.trafikanten.views.GenericSelectStationView;

public class SelectRouteStationView extends GenericSelectStationView {
	public static final String STATIONLIST_PARCELABLE = "stationList";
	private Button multiSelectButton;
	
	private ArrayList<StationData> selectedStations = new ArrayList<StationData>();
	
	final static private int MULTISELECT_DISABLED = 0;
	final static private int MULTISELECT_ENABLED = 1;
	
	private int multiSelect = MULTISELECT_DISABLED;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.selectstation_route);
		isRealtimeSelector = false;
        super.onCreate(savedInstanceState);

		/*
		 * Search code
		 */
		final Intent intent = getIntent();
		final String action = intent.getAction();
		if (action != null) {
			if (Intent.ACTION_SEARCH.equals(action)) {
				final String query = intent.getStringExtra(SearchManager.QUERY);
				doSearch(query, 0);
			} else if (StationSearchProvider.SEARCHTYPE_ROUTE.equals(action)) {
		    	// Return single realtime station;
				
				final Uri queryData = intent.getData();
				String stopName = queryData.getQueryParameter("name");
				String extra = queryData.getQueryParameter("extra");
				int stationId = Integer.parseInt(queryData.getQueryParameter("id"));
				int type = Integer.parseInt(queryData.getQueryParameter("type"));
				if (type > 0) {
					//  We have a address/poi or something, do a search for that instead.
					doSearch(stopName, stationId);
				} else {
			    	
			    	final StationData station = new StationData(stopName, extra, stationId);
			    	multiSelect = MULTISELECT_DISABLED;
			    	stationSelected(station);
			    	return;					
				}

		    }
		}
		
		multiSelectButton = (Button) findViewById(R.id.multiSelectButton);
		multiSelectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch(multiSelect) {
				case MULTISELECT_DISABLED:
					/*
					 * Multiselect was disabled, lets enable it and refresh.
					 */
					multiSelect = MULTISELECT_ENABLED;
					refreshMultiSelect();
					multiSelectButton.setText(android.R.string.ok);
					break;
				case MULTISELECT_ENABLED:
					/*
					 * Multiselect was enabled, this means button click = return with stations
					 */
					
					/*
					 * Update history for all the stations we ended up using
					 */
					for(StationData station : selectedStations) {
						mStationDbAdapter.stationUsed(station);
					}

					/*
					 * Return list of stations
					 */
					/*Bundle bundle = new Bundle();
					bundle.putParcelableArrayList(STATIONLIST_PARCELABLE, selectedStations);
					
					final Intent intent = new Intent();
			        intent.putExtras(bundle);
			        setResult(RESULT_OK, intent);*/
					SelectRouteView.Activity_Result = selectedStations;
			        finish();
				}
			
			}
		});
		multiSelectButton.setVisibility(View.VISIBLE);
		
		new ShowTipsTask(this, SelectRouteStationView.class.getName(), R.string.tipSelectRoute, 35);
	}
	
	private void refreshMultiSelect() {
		int layout = multiSelect == MULTISELECT_ENABLED ? R.layout.selectstation_list_multiselect : R.layout.selectstation_list;
		selectedStations.clear();
		setAdapterLayout(layout);
	}
	
	/*
	 * Handler for station selected
	 */
	@Override
	public void stationSelected(StationData station) {
		switch(multiSelect) {
		case MULTISELECT_DISABLED:
			/*
			 * Multiselect is disabled, return as normal
			 */
			mStationDbAdapter.stationUsed(station);

			/*Bundle bundle = new Bundle();
			bundle.putParcelable(StationData.PARCELABLE, station);
			final Intent intent = new Intent();
	        intent.putExtras(bundle);
	        setResult(RESULT_OK, intent);*/
			
			SelectRouteView.Activity_Result = new ArrayList<StationData>();
			SelectRouteView.Activity_Result.add(station);
			
	        finish();
	        break;
		case MULTISELECT_ENABLED:
			/*
			 * With multiselect enabled stationSelected means toggle.
			 */
			
			if (selectedStations.contains(station)) {
				selectedStations.remove(station);
			} else {
				selectedStations.add(station);
			}
		}
	}
	
	/*
	 * This pipes data backwards through the activity stack.
	 * The basic idea, go into route
	 *  A: = Opens SelectRouteView
	 *  click from to:
	 *  B: = open new SelectRouteStationView
	 *  search on this page to:
	 *  C: = open new SelectRouteStationView further down in the stack.
	 *  
	 *  If we get activity result here, we are B getting result from C, and must route that back to A.
	 * 
	 * @see com.neuron.trafikanten.views.GenericSelectStationView#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) return;
		
		final Intent intent = new Intent();
		Bundle bundle = data.getExtras();
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
	}

	@Override
	public boolean route_isStationSelected(StationData station) {
		return (multiSelect == MULTISELECT_ENABLED) && selectedStations.contains(station); 
	}

	@Override
	public void setProgressBar(boolean value) {
		setProgressBarIndeterminateVisibility(value);
	}
	
	@Override
	public int getInfoHelpText() {
		return R.string.searchStationRouteNoStationsFound;
	}
	
	@Override
	public int getViewType() {
		return TYPE_ROUTE;
	}
}
